# -*- coding: utf-8 -*-
# @Time    : 2019/9/27 14:29
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : study_content_type.py

# 需求：博客(comment)  、文章(comment)  、图片(comment)，三个模块功能下都有评论功能，#新增允许评论的模块
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission


class Comment(models.Model):
    """
    评论关联三个类型外键，
    也就是一条记录三个类型只有一个有值，
    新增模块时代码扩展性较弱，
    目标comment类变得通用
    """
    author = models.ForeignKey(to=User, on_delete=models.CASCADE)
    body = models.TextField(blank=True, null=True)
    # pic = models.ForeignKey(to=Picture, on_delete=models.CASCADE, null=True)
    # post = models.ForeignKey(to=Post, on_delete=models.CASCADE, null=True)
    # article = models.ForeignKey(to=Article, on_delete=models.CASCADE, null=True)
    # 通用外键的三个字段
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.IntegerField()   # 其他表的主键，下面使用该通用类外键表的主键
    content_object = GenericForeignKey("content_type", "object_id")


class Post(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField(blank=True, null=True)
    # 添加通用类外键
    comments = GenericRelation(Comment)  # 默认是删除级联


class Article(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField(blank=True, null=True)
    comments = GenericRelation(Comment)


class Picture(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    body = models.TextField(blank=True, null=True)
    comments = GenericRelation(Comment)


# 1.app_label 2.model 3.id

